package com.feixiang.springbootinit.task;

import cn.hutool.core.date.DateUtil;
import com.feixiang.springbootinit.annotation.MonitorTask;
import com.feixiang.springbootinit.constant.WxConstant;
import com.feixiang.springbootinit.model.entity.wechat.ChatData;
import com.feixiang.springbootinit.model.entity.wechat.QwMessage;
import com.feixiang.springbootinit.processor.SessionArchiveBatchProcessor;
import com.feixiang.springbootinit.processor.SessionArchiveProcessor;
import com.feixiang.springbootinit.service.QwMessageService;
import com.feixiang.springbootinit.service.SessionArchiveService;
import com.feixiang.springbootinit.utils.SessionArchiveUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
/**
 * 定时任务(简单版本)
 */
public class ChatDataTask {
    @Autowired
    private QwMessageService messageService;
    @Autowired
    private SessionArchiveService sessionArchiveService;
    @Autowired
    private SessionArchiveBatchProcessor sessionArchiveBatchProcessor;
    @Value("${task.autoStart}")
    private boolean autoStart;

    //@Scheduled(fixedRate = 2000)
//    public void executeDirectly() {
//        log.info("开始执行定时任务,当前时间: {}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        int maxRetry = 3; // 最大重试次数
//        int retryCount = 0;
//        boolean success = false;
//        while (retryCount < maxRetry && !success) {
//            try {
//                Long maxSeq = messageService.getMaxSeq();
//                log.info("当前seq值: {}", maxSeq);
//                String chatData = sessionArchiveService.getChatData(maxSeq != null ? maxSeq : 0L);
//                log.info("开始拉取数据:{}", chatData);
//                if (chatData != null) {
//                    List<QwMessage> messages = sessionArchiveService.decodeChatData(chatData);
//                    log.info("拉取解密数据: {}", messages);
//                }
//                success = true; // 标记成功
//            } catch (Exception e) {
//                retryCount++;
//                log.error("定时任务执行失败 (重试 {}/{}), 错误原因: {}", retryCount, maxRetry, e.getMessage());
//                if (retryCount >= maxRetry) {
//                    log.error("达到最大重试次数，任务终止");
//                }
//                try {
//                    Thread.sleep(8000); // 重试间隔8秒
//                } catch (InterruptedException ignored) {}
//            }
//        }
//    }

    /**
     * 单线程拉取企微会话存档，多线程处理消息。
     * todo 定时任务多线程
     */

    @MonitorTask("会话存档拉取任务")
    @Scheduled(fixedRateString = "${task.fixedRate}")
    public void pullSessionArchive() {
        if (!autoStart) {
            log.info("定时任务未启用,等待启用");
            return;
        }
        //log.info("开始执行定时任务,当前时间: {}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        Long maxSeq = messageService.getMaxSeq();
        log.info("开始拉取会话存档,当前最大seq为{}", maxSeq);
        List<ChatData> chatData = SessionArchiveUtil.getChatData(SessionArchiveBatchProcessor.getGlobalSdkInstance(), maxSeq != null ? maxSeq : 0L, 100L, null, null, null);
        if (chatData == null) {
            log.info("拉取chatData为空");
            return;
        }
        log.info("拉取chatData数据:{}", chatData);
        List<QwMessage> messages = sessionArchiveBatchProcessor.processMessages(chatData);
        log.info("处理后的messages数据:{}", messages);
    }
}